package com.lkd.handler;


import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.StatusInfo;
import com.lkd.contract.VmStatusContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import com.sun.tools.javac.Main;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.util.*;

@Component
@Slf4j
@Topic(TopicConfig.VMS_STATUS_TOPIC) // 维修工单自动创建
public class AutoRepairTaskHandler implements MsgHandler {

    @Autowired
    private VMService vmService;

    @Autowired
    private TaskService taskService;

    @Override
    public void process(String jsonMsg) throws IOException {
        log.info("开始自动创建维修工单");
        VmStatusContract vmStatusContract = JsonUtil.getByJson(jsonMsg, VmStatusContract.class);
        List<StatusInfo> statusInfo = vmStatusContract.getStatusInfo();
        statusInfo.forEach(status -> {
            if (!(status.isStatus())) {
                // 设备有问题,创建维修工单
                // 查询售货机信息
                VmVO vmVO = vmService.getVMInfo(vmStatusContract.getInnerCode());
                if (ObjectUtils.isEmpty(vmVO)){
                    return;
                }
                // 获取当前区域 工单最少的用户
                int userId = taskService.getLeastUser(vmVO.getRegionId(), true);
                if (userId != 0){
                    TaskViewModel taskViewModel = new TaskViewModel();
                    taskViewModel.setUserId(userId);
                    taskViewModel.setCreateType(0); // 自动创建工单
                    taskViewModel.setDesc("自动创建工单");
                    taskViewModel.setInnerCode(vmVO.getInnerCode()); // 售货机编码
                    taskViewModel.setProductType(VMSystem.TASK_TYPE_REPAIR);  // 维修工单
                    taskViewModel.setAssignorId(0); // 自动工单
                    taskService.createTask(taskViewModel);
                }
            }
        });
    }

}
